package club.koorikaze;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;


public class dom4jover {

    private String fileName = "src/test.xml";

    @Test
    public void create() throws Exception {

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");

        //如果里面不加东西只会有结束标签
        Element first = root.addElement("first");

        Element first1 = first.addElement("name");
        first1.addText("one");
        first1.addAttribute("id","11");
        first1.addAttribute("sex","male");

        Element first2 = first.addElement("do");
        first2.addText("run");
        first2.addAttribute("id","12");

        Element second = root.addElement("second");

        Element second1 = second.addElement("name");
        second1.addText("two");
        second1.addAttribute("id","21");
        second1.addAttribute("sex","female");

        Element second2 = second.addElement("do");
        second2.addText("talk");
        second2.addAttribute("id","22");

        //输出
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        // 设置换行 为false时输出的xml不分行
        outputFormat.setNewlines(true);
        // 生成缩进
        outputFormat.setIndent(true);
        // 指定使用tab键缩进
//        outputFormat.setIndent("  ");
        // 不在文件头生成  XML 声明 (<?xml version="1.0" encoding="UTF-8"?>)
//        outputFormat.setSuppressDeclaration(true);
        // 不在文件头生成  XML 声明 (<?xml version="1.0" encoding="UTF-8"?>)中加入encoding 属性
//        outputFormat.setOmitEncoding(true);

        XMLWriter writer = new XMLWriter(new OutputStreamWriter(
                new FileOutputStream(fileName), "UTF-8") , outputFormat);
        //写入
        writer.write(document);
        writer.close();

    }

    @Test
    public void update() throws Exception {

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(fileName);

        Element rootElwment = document.getRootElement();

        for ( Iterator iterator = rootElwment.elementIterator() ; iterator.hasNext() ; ) {
            Element itemElement = (Element) iterator.next();

            System.out.println(itemElement.getQName());

            for ( Iterator attIterator = itemElement.attributeIterator() ; attIterator.hasNext() ; ) {
                Attribute attribute = (Attribute) attIterator.next();
                System.out.println(attribute.getQName());
                System.out.println(attribute.getText());
            }

        }

    }
}
